<template>
  <!--  <div>-->
  <!--    <div style=" padding: 20px;">-->
  <j-modal
    :confirmLoading="confirmLoading"
    :dialogStyle="dialogStyle"
    :title="title"
    :visible="visible"
    :width="800"
    cancelText="关闭"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <div :spinning="confirmLoading">
      <!--      <a-form :form="form">-->
      <a-row :gutter="24">
        <a-col :span="24" class="someSpace">
          <a-card class="cardShadow" title="">
            <a-spin :spinning="confirmLoading">
              <a-form :form="form0">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="年份">
                  <a-select
                    v-decorator="[
                      'year',
                      {
                        rules: [
                          {
                            required: true,
                            message: '年份不能为空!',
                          },
                        ],
                      },
                    ]"
                    placeholder="请选择年份"
                  >
                    <a-select-option v-for="(i, index) in yearList" :key="index" :value="i.key"
                      >{{ i.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-form>
              <a-row class="cTradeTitle">
                <h2>GDP能耗</h2>
              </a-row>
              <a-form :form="form1">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="完成率">
                  <a-input
                    v-decorator="[
                      'comoletionRate',
                      {
                        rules: [
                          {
                            required: true,
                            message: '完成率必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="请输入完成率"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="目标">
                  <a-input
                    v-decorator="[
                      'target',
                      {
                        initialValue: 14,
                        rules: [
                          {
                            required: true,
                            message: '目标必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="目标"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="当年进度">
                  <a-input
                    v-decorator="[
                      'comoletionRateYear',
                      {
                        rules: [
                          {
                            required: true,
                            message: '当年进度为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="当年进度"
                    suffix="%"
                  />
                </a-form-item>
              </a-form>
              <a-row class="cTradeTitle">
                <h2>GDP碳排放</h2>
              </a-row>
              <a-form :form="form2">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="完成率">
                  <a-input
                    v-decorator="[
                      'comoletionRate',
                      {
                        rules: [
                          {
                            required: true,
                            message: '完成率必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="请输入完成率"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="目标">
                  <a-input
                    v-decorator="[
                      'target',
                      {
                        initialValue: 20.9,
                        rules: [
                          {
                            required: true,
                            message: '目标必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="目标"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="当年进度">
                  <a-input
                    v-decorator="[
                      'comoletionRateYear',
                      {
                        rules: [
                          {
                            required: true,
                            message: '当年进度为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="当年进度"
                    suffix="%"
                  />
                </a-form-item>
              </a-form>
              <a-row class="cTradeTitle">
                <h2>工业增加值能耗</h2>
              </a-row>
              <a-form :form="form3">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="完成率">
                  <a-input
                    v-decorator="[
                      'comoletionRate',
                      {
                        rules: [
                          {
                            required: true,
                            message: '完成率必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="请输入完成率"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="目标">
                  <a-input
                    v-decorator="[
                      'target',
                      {
                        initialValue: 14,
                        rules: [
                          {
                            required: true,
                            message: '目标必须为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="目标"
                    suffix="%"
                  />
                </a-form-item>
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="verticalCenter" label="当年进度">
                  <a-input
                    v-decorator="[
                      'comoletionRateYear',
                      {
                        rules: [
                          {
                            required: true,
                            message: '当年进度为正数，最多包含一位小数!',
                            pattern: /^\d+(\.\d)?$/,
                          },
                        ],
                      },
                    ]"
                    placeholder="当年进度"
                    suffix="%"
                  />
                </a-form-item>
              </a-form>
              <!--                <a-button :loading="confirmLoading" class="button" icon="upload" type="primary" @click="handleOk()">提交-->
              <!--                </a-button>-->
            </a-spin>
          </a-card>
        </a-col>
      </a-row>
      <!--      </a-form>-->
    </div>
  </j-modal>
  <!--    </div>-->
  <!--  </div>-->
</template>

<script>
import { getAction, httpAction } from '@api/manage'
import pick from 'lodash.pick'
import { set } from 'xe-utils/methods'

export default {
  name: 'targetTracking',
  data() {
    return {
      model: '',
      confirmLoading: false,
      title: '',
      visible: false,
      dialogStyle: {
        top: '100px',
        // right:"20px",
      },
      yearList: [
        { key: '2021', name: '2021' },
        { key: '2022', name: '2022' },
        { key: '2023', name: '2023' },
        { key: '2024', name: '2024' },
      ],
      form0: this.$form.createForm(this),
      form1: this.$form.createForm(this),
      form2: this.$form.createForm(this),
      form3: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        add: '/carbon/targetTracke/add',
        edit: '/carbon/targetTracke/edit',
      },
    }
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.visible = true
      this.form0.resetFields()
      this.form1.resetFields()
      this.form2.resetFields()
      this.form3.resetFields()
      this.getData(record.year)
    },
    getData(year) {
      let that = this
      if (year) {
        let httpurl = '/carbon/targetTracke/list'
        getAction(httpurl, { year: year }).then((res) => {
          if (res.success) {
            let data = res.result
            this.model = Object.assign({}, data)
            this.$nextTick(() => {
              this.form0.setFieldsValue(pick(this.model.records[0], 'year'))
              this.form1.setFieldsValue(
                pick(this.model.records[0], 'id', 'comoletionRate', 'target', 'comoletionRateYear'),
              )
              this.form2.setFieldsValue(
                pick(this.model.records[1], 'id', 'comoletionRate', 'target', 'comoletionRateYear'),
              )
              this.form3.setFieldsValue(
                pick(this.model.records[2], 'id', 'comoletionRate', 'target', 'comoletionRateYear'),
              )
            })
          }
        })
      }
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.model = ''
      this.$parent.$parent.loadData()
      this.form0.resetFields()
      this.form1.resetFields()
      this.form2.resetFields()
      this.form3.resetFields()
    },
    async handleOk() {
      try {
        const forms = [this.form0, this.form1, this.form2, this.form3]
        const formDataAll = { form1: {}, form2: {}, form3: {} }
        let httpurl = ''

        const yearValues = await this.validateForm(this.form0)
        formDataAll.year = yearValues.year
        for (let i = 1; i < forms.length; i++) {
          const values = await this.validateForm(forms[i])
          formDataAll[`form${i}`] = { ...values, year: formDataAll.year, name: this.getName(i) }

          const id = ''
          let length = Object.keys(this.model).length
          console.log(length)
          if (length > 0) {
            id = this.model.records[i - 1].id
          }
          httpurl = id ? this.url.edit : this.url.add
          console.log(httpurl)

          const formData = formDataAll[`form${i}`]
          if (id) {
            formData.id = id
          }

          const method = id ? 'put' : 'post'
          const res = await httpAction(httpurl, formData, method)
          if (!res.success) {
            this.$message.error(res.message)
            return // Stop further execution if there's an error
          }
        }
        this.$message.success('保存成功')
        this.$emit('refresh')
        this.close()
      } catch (error) {
        // this.$message.error(error.message);
      } finally {
        this.confirmLoading = false
      }
    },

    validateForm(form) {
      return new Promise((resolve, reject) => {
        form.validateFields((err, values) => {
          if (err) {
            reject(new Error('Validation failed'))
          } else {
            resolve(values)
          }
        })
      })
    },
    getName(index) {
      const names = ['GDP能耗', 'GDP碳排放', '工业增加值能耗']
      return names[index - 1] || ''
    },
  },
}
</script>

<style lang="stylus" scoped>
.cardShadow {
  //box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  border none
}

.verticalCenter {
  //  垂直居中
}

.someSpace {
  margin-bottom: 24px;
}

.cTradeTitle {
  background-color #eeeeee
  padding-left 20px
  padding-top 8px
  margin-bottom 30px
  margin-top 10px
}

.button {
  margin-left: 50%;
  transform: translateX(-50%);
}
</style>
